package hw.ats.news.activity.news;

import hw.ats.news.R;
import hw.ats.news.activity.DBAwareActivity;
import hw.ats.news.ds.NewsParser;
import hw.ats.news.model.News;
import hw.ats.news.ui.BottomTabHostProvider;
import hw.ats.news.ui.CommonUI;
import hw.ats.news.ui.NewsResourceHolder;
import hw.ats.news.util.App;
import hw.ats.news.util.DataLoader;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ListView;

import com.humanwares.ui.asyncimage.ImageDisplayer;
import com.humanwares.ui.asyncimage.ImageReceivedCallback;
import com.humanwares.ui.asyncimage.ImageReceiver;
import com.humanwares.ui.tabbar.TabHost;
import com.tattermedia.allthataudio.misc.DebugFlag;

// 더보기 > 분류를 선택하면 사용되는 액티비티이나 요청으로 인해 사용하지 않음
public class CateAct extends DBAwareActivity implements ImageReceivedCallback {
	private final static String TAG = "CateAct";
	
	private List<News> items = new ArrayList<News>();
	private ListView listView = null;
	private TabHost navbar = null;
	
	// 페이징
	private int start = 0;
	private int rows = App.ROW_PER_PAGE;
	private boolean hasNext = true;
	
	private boolean thumbDisplay = false;
	
	private int catePage = 0;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
        thumbDisplay = pref.getBoolean("pref_list_thumb", true);
        
        loadData();
        
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        setContentView(R.layout.act_cate);
        
        // 탭바 초기화
        navbar = CommonUI.renderTabBar(this, BottomTabHostProvider.TAB5);
        
		// 네비게이션바 제목
        CommonUI.renderAppTitle(this);
        
        // 우측 네비게이션 버튼 = All That 화면이동
        CommonUI.addRightNavigationButtonAllThatEvent(this);
        
        // 좌측 네비게이션 버튼 = 검색화면이동
        CommonUI.addLeftNavigationButtonSearchEvent(this);
        
        listView = (ListView)findViewById(R.id.news_list);
        listView.setAdapter(new CateAdapter(this));
        listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				News news = items.get(position);
				Intent intent = new Intent(CateAct.this, ViewAct.class);
				intent.putExtra(App.INTENT_EXTRA_NEWS_UID, news.uid);
				intent.putExtra(App.INTENT_EXTRA_ACT_NAME, CateAct.class.getName());
			    startActivity(intent);
			}
        });
    }
    
    @Override
	protected void onDestroy() {
		super.onDestroy();
		if (DebugFlag.isLogEnabled()) Log.d(TAG, "onDestroy()");
		closeDatabase();
	}
    
    /**
     * 이미지 로더
     */
	public void onImageReceived(ImageDisplayer displayer) {
		this.runOnUiThread(displayer);
	}
	
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        int visibility = navbar.getVisibility();
        navbar.setVisibility(visibility == View.VISIBLE ? View.INVISIBLE : View.VISIBLE);
        return false;
    }
    
    
    private void loadData() {
    	Log.d("CATEGORY LOAD DATA","LOADING CATEGORY DATA");
		int cateUid = getIntent().getIntExtra(App.INTENT_EXTRA_CATE_UID, 0);
		NewsParser parser = new NewsParser();
		List<News> list = parser.parse(App.NEWS_CATE_XML_URL + cateUid+"&page="+catePage);
		for (int i = 0, len = list.size(); i < len; i++) {
			News news = list.get(i);
			News dbNews = News.load(getReadableDatabase(), news.uid);
			
			if (dbNews == null) {
//				DataLoader.loadNewsBody(getDBHelper(), news, false);
				news.insert(getWritableDatabase());
				
			} else {
				news = dbNews;
			}
			
			items.add(news);
		}
		if (items.size() > 0) {
			hasNext = true;
		} else {
			hasNext = false;
		}
	}
    
    
	private void loadData_legacy() {
		int cateUid = getIntent().getIntExtra(App.INTENT_EXTRA_CATE_UID, 0);
		List<News> newItems = News.list(getReadableDatabase(), cateUid, start, rows);
		if (newItems.size() > 0) {
			items.addAll(newItems);
			hasNext = true;
		} else {
			hasNext = false;
		}
	}
	
	/**
	 * 다음 페이지 데이터 조회
	 */
    private void loadNextData() {
    	start += App.ROW_PER_PAGE;
    	new AsyncTask<String, Integer, Boolean>() {
    		private ProgressDialog progressDialog;
    		
    		@Override
    		protected void onPreExecute() {
    			super.onPreExecute();
    	    	progressDialog = ProgressDialog.show(
    	        		CateAct.this, "알림", "글을 조회하고 있습니다.", true, false);
    		}
    		
			@Override
			protected Boolean doInBackground(String... params) {
				loadData();
				return true;
			}
			
			@Override
			protected void onProgressUpdate(Integer... progress) {
			}

			@Override
			protected void onPostExecute(Boolean result) {
				((BaseAdapter)listView.getAdapter()).notifyDataSetChanged();
				progressDialog.dismiss();
			}

			@Override
			protected void onCancelled() {
				super.onCancelled();
				progressDialog.dismiss();
			}
		}.execute();
    }
	
	private class CateAdapter extends BaseAdapter {
		private final static String TAG = "CateAdapter";
	   	private final Activity context;

        public CateAdapter(Activity context) {
        	this.context = context;
        }

        public int getCount() {
        	if (items == null)
        		return 0;
        	
        	return items.size() + (hasNext ? 1 : 0);
        }

        public Object getItem(int position) {
            return items.get(position);
        }

        public long getItemId(int position) {
            return position;
        }
        
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = convertView;
            NewsResourceHolder holder = null;
            
            // 페이징
            if (items.size() == position) {
            	LayoutInflater vi = context.getLayoutInflater();
            	view = vi.inflate(R.layout.row_more_article, null);
            	ImageButton btn = (ImageButton)view.findViewById(R.id.row_more_btn);
            	btn.setOnClickListener(new OnClickListener() {
        			@Override
        			public void onClick(View v) {
        				loadNextData();
        			}
        		});
            	return view;
            }
            
            if (view == null || view.getTag() == null) {
            	LayoutInflater vi = context.getLayoutInflater();
            	if (thumbDisplay)
            		view = vi.inflate(R.layout.row_news_type2, null);
            	else
            		view = vi.inflate(R.layout.row_news_type1, null);
                holder = new NewsResourceHolder(view);
                view.setTag(holder);
            } else {
            	holder = (NewsResourceHolder)view.getTag();
            }

            News entry = items.get(position);
    		if (entry == null) {
    			return view;
    		}
    		
            if (DebugFlag.isLogEnabled()) 
            	Log.d(TAG,
            		"pos="+position+
            		" img="+holder.imageView+
            		" cv="+convertView+
            		" par="+parent);
            
            if (holder.imageView != null) {
            	holder.imageView.setTag(position);
            	holder.imageView.setImageBitmap(null);
                new ImageReceiver(entry.thumb_default, (ImageReceivedCallback)context, 
                		holder.imageView, getThumbPath(), position);
            }
            
            if (holder.titleView != null)
            	holder.titleView.setText(entry.title);
            
            if (holder.detailView != null) {
            	int len = entry.body_text.length();
            	if (len > 256) len = 256;
            	holder.detailView.setText(entry.body_text.substring(0, len));
            }
    		
    		return view;
        }
	}
}
